var form;
var table;
var layer;
var upload;
var $;
layui.use(['layer','form','table','upload'],function(){
    form = layui.form;
    table=layui.table;
    layer=layui.layer;
    upload=layui.upload;
    $=layui.$;

    //商品信息
    showtables();


    //修改商品状态
    form.on('switch', function(data){
        var flag=data.elem.checked;

        //获取商品状态
        var state=null;
        if(flag){
            state=1;
        }else{
            state=2;
        }

        //商品id
        var productId=data.elem.value;
        $.ajax({
            url: "/SyOperationController/updProductSate",
            dataType: "json",
            type:"post",
            data:{"state":state,"productId":productId},
            success: function (data) {
                if(data.code==0){
                    layer.msg('修改成功',{icon: 1});
                }else{
                    layer.msg('修改失败',{icon: 2});
                }
            }
        });
    });

    //商品分类下拉菜单
    $.ajax({
        url: "/SyOperationController/selProductCategorySelect",
        type: "get",
        dataType: "json",
        success: function (data) {
            var i="<option value=''>请选择商品分类</option>";
            for(var a=0;a<data.data.length;a++){
                i+="<option value='"+data.data[a].category_id+"'>"+data.data[a].categroy_name+"</option>";

            }
            $(".gory").html(i);
            form.render();
        }
    });


});


/*导入文件开始*/
function couImport(){
    layer.open({
        type:1,
        title:"导入商品",
        area:['250px','200px'],
        shade:0.4,
        offset:'auto',
        content:"<button class='layui-btn' id='btn' style='    margin-top: 19%;margin-left: 32%;'>选择文件</button>",
        success:function(layero,index){
            upload.render({
                elem:"#btn",
                url : '/SyOperationController/addInsimportExcel',
                done:function (data) {
                    if(data.code==0){
                        layer.msg('导入成功',{icon:1});
                        layer.close(index);
                    }else{
                        layer.msg('导入失败',{icon:2});
                    }
                },
                drag:true,
                accept:'file',
                multiple:true
            })
        }
    })
}
/*导入文件结束*/

//重置按钮
$('#resetBtn').on('click',function(){
    $("input").val("");
    $(this).find("option:selected").removeAttr("selected");
    showtables();
})
//商品数据表格 搜索按钮
function search(){
    var name1=$("input[name='name1']").val();
    var name2=$("#gory option:selected").val();
    var name3=$("#name3 option:selected").val();
    var name4=$("input[name='name4']").val();
    var name5=$("input[name='name5']").val();

    $.ajax({
        url: "/SyOperationController/selProduct",
        type: "post",
        dataType: "json",
        data:{"name1":name1,"name2":name2,"name3":name3,"name4":name4,"name5":name5,"productSate":3},
        success: function (data) {
            getTable(data.data);
        }
    })
}

//展示table表格
function showtables(){
    $.post("/SyOperationController/selProduct",{"productSate":3}, function (data) {

        getTable(data.data);
    });
}

//商品数据表格
function getTable(data){
    var tb1;
    tb1=table.render({
        elem:"#table_id",//容器
        data:data,
        title:"商品数据列表",
        limit:5,//分页显示条数
        toolbar:"#toolbar_id",
        page:{
            layout:['prev','page','next','limit','skip','count'],
            limits:[5,10,15,20],
            first:"首页",
            last:"尾页",
        },
        cols:[[//定义列
            {type:'checkbox',align:'center',width:45},//复选框靠左
            {field:"product_code",title:"商品编号",align:'center'},
            {field:"main_image",title:"商品图片",align:'center',width:130,templet:function(data){
                    return "<img src='"+data.main_image+"' height='100px'>"
                }},
            {field:"product_name",title:"商品名称",align:'center',width:145},
            {field:"currentprice_product",title:"商品价格",align:'center',templet:function(data){
                    return "￥"+data.currentprice_product;
                }},
            {field: 'state', title: '上架/下架',align: 'center',width:100, templet: function (data) {
                    if(data.state==1){
                        return  "<input type='checkbox' checked='' name='open' lay-skin='switch' lay-filter='switchTest' lay-text='上架|下架' value=\"" + data.product_id + "\">";
                    }else if(data.state==2){
                        return  "<input type='checkbox' name='close' lay-skin='switch' lay-text='上架|下架' value=\"" + data.product_id + "\">";
                    }else{
                        return  "<input type='checkbox' name='close' lay-skin='switch' lay-text='上架|下架' value=\"" + data.product_id + "\">";
                    }
                }},
            {field:"categroy_name",title:"商品分类",align:'center',templet: function (data) {
                    if(data.categroy_name==undefined){
                        return "未分类";
                    }else{
                        return data.categroy_name;
                    }
                }},
            {field:"product_label",title:"商品标签",align:'center',templet: function (data) {
                    if(data.product_label==undefined||data.product_label==''){
                        return "无";
                    }else{
                        return data.product_label;
                    }
                }},
            {field:"product_sate",title:"审核状态",align:'center',width:90, templet: function (d) {
                    if(d.product_sate==3){
                        return "<p style='margin-top:0px;'>审核通过</p>" +
                            "<p><a onclick='javascript:ProductExamin(\""+d.product_id+"\");' style='color:#1ABC9C;cursor:pointer;text-decoration: none;'>审核详情</a></p>"
                    }
                }},
            {field:"",title:"操作",align:'center',width:125,templet: function (d) {
                    return "<a style='color:#009688;cursor:pointer;float: left;margin-left: 14px;line-height: 15px;' onclick='selProduct2(\""+d.product_id+"\");'>查看</a>  " +
                        "<a style='color:#009688;cursor:pointer;float: left;margin-left: 15px;line-height: 15px;' onclick='ProductUpdate(\""+d.product_id+"\");'>编辑</a><br/>   " +
                        "<a style='color:#009688;cursor:pointer;float: left;margin-left: 14px;line-height: 15px;' onclick='selProductLog(\""+d.product_id+"\");'>日志</a>  " +
                        "<a style='color:#009688;cursor:pointer;float: left;margin-top: -15px;margin-left: 58px;line-height: 15px;'onclick='delProduct(\""+d.product_id+"\");'>删除</a>  " ;
                }}
        ]]
    });

}

//刷新
function refresh() {
    location.reload();
}

//高级检索
function sousuo(){
    var productCode=$("input[name='productCode1']").val();
    var productName=$("input[name='productName1']").val();
    var currentpriceProduct=$("input[name='currentpriceProduct1']").val();
    var categoryId=$("input[name='categoryId1']").val();
    var state=$("input[name='state1']").val();
    var productLabel=$("input[name='productLabel1']").val();

    $.post("/SyOperationController/selProduct",
        {"productCode":productCode,"name1":productName,"currentpriceProduct":currentpriceProduct,
            "name2":categoryId,"name3":state,"name4":productLabel,"productSate":3},
        function (data) {
            getTable(data.data);
        });
}
//点击查检索页面
function retrieve() {

    layer.open({
        type : 2,//弹出层的类型
        id:1,
        title : "<div style='color:#666666;font-weight: 600;background: #F8F8F8;'>样品分类</div>",
        area : [ '670px', '510px' ],
        maxmin: true,
        shade : 0.4,
        offset: 'auto',
        content :"ProductRetrieve.html",
        success:function(){
        }
    });
    window.layer_1=layer;
}

//点击查看按钮弹出详情页面
function selProduct2(productId){
    var index = layer.open({
        type:2,
        title:"商品详情",
        area:['800px','600px'],
        shade:0.4,
        offset:'auto',
        maxmin: true,
        content:"/operation/comment/TeaCommodityView.html",
        success:function(layero,index) {
            //查找当前引入的iframe内容
            var obj = layero.find('iframe').contents();
            //根据选择器选择input,并设置值
            obj.find('#courseId').val(productId);
            addOperationLog();
        }
    });
    layer.full(index);
}

//添加查看操作日志
function addOperationLog() {
    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象
    $.ajax({
        url:"/personnel/addOperationLog",
        type:"post",
        dataType:"json",
        data:{"tablename":"商品列表","type":5,"mid":create.user_id,"remark":"查看商品详情"}
    });
}


//点击编辑
function ProductUpdate(productId){
    localStorage.setItem("productId",productId); //商品ID
    ProductUpdateLayer();
}
//弹出修改页面
function  ProductUpdateLayer() {
    layer.open({
        type : 2,//弹出层的类型
        id:1,
        title : "<div style='color:#666666;font-weight: 600;background: #F8F8F8;'>修改商品</div>",
        area : [ '1200px', '560px' ],
        maxmin: true,
        shade : 0.4,
        offset: 'auto',
        content :"ProductUpdate.html",
        success:function(layero,index){}
    });
    window.layer_1=layer;
}

//删除商品
function delProduct(id) {
    var create=localStorage.getItem("user");
    create=JSON.parse(create);//将获取json字符串转json对象
    $.ajax({
        //url: "/SyOperationController/delProduct",
        url: "/SyOperationController/upProduct",
        type: "post",
        dataType: "json",
        data:{"productId":id,"mid":create.user_id},
        success: function (data) {
            if(data.code==0){
                //search();
                showtables();
                layer.msg('删除成功')
            }else{
                layer.msg('修改失败')
            }
        }
    });
}

//点击商品审核
function ProductExamin(productId){
    localStorage.setItem("productId",productId); //商品ID
    auditLogging();
}
//审核详情
function auditLogging() {
    //$("#product_id").val(id);
    layer.open({
        type : 2,
        id:1,
        title : "<div style='color:#666666;font-weight: 600;background: #F8F8F8;'>审核详情</div>",
        area : [ '810px', '450px' ],
        maxmin: true,
        shade : 0.4,
        offset: 'auto',
        content :"ProductExamin.html",
        success:function(){
        }
    });
    //window.layer_1=layer;
}


//查看商品日志
function selProductLog(product_id) {
    location.href="ProductLog.html?"+product_id;
}

//添加商品
function productAdd() {
    location.href="ProductAdd.html?";
}


//商品分类
selProductCategory()
function selProductCategory() {
    $.ajax({
        url: "/SyOperationController/selProductCategory",
        type: "post",
        dataType: "json",
        success: function (data) {
            shouZTree(data.data);
        }
    })
};


function shouZTree(data){
    $(function(){
        //点击节点获取值
        function zTreeOnClick(event, treeId, treeNode) {
            $.post("/SyOperationController/selProduct",{"name2":treeNode.id,"productSate":3}, function (data) {
                getTable(data.data);
            });
            return false;
        };
        var ZtreeTile;
        function OnRightClick(event, treeId, treeNode) {
            if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
                zTree.cancelSelectedNode();
                showRMenu("root", event.clientX, event.clientY);
            } else if (treeNode && !treeNode.noR) {
                ZtreeTile=treeNode;
                showRMenu("node", event.clientX, event.clientY);
            }
        }
        function showRMenu(type, x, y) {
            $("#rMenu ul").show();
            if (type=="root") {
                $("#m_del").hide();
                $("#m_check").hide();
                $("#m_unCheck").hide();
            } else {
                $("#m_del").show();
                $("#m_check").show();
                $("#m_unCheck").show();
            }
            y += document.body.scrollTop;
            x += document.body.scrollLeft;
            rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
            $("body").bind("mousedown", onBodyMouseDown);
        }
        function hideRMenu() {
            if (rMenu) rMenu.css({"visibility": "hidden"});
            $("body").unbind("mousedown", onBodyMouseDown);
        }
        function onBodyMouseDown(event){
            if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
                rMenu.css({"visibility" : "hidden"});
            }
        }


        //添加节点
        $("#m_add").bind("click",function() {
            var parentId=ZtreeTile.id;
            layer.open({
                type:1,
                title:"添加分类",
                area:['420px','200px'],
                offset:'auto',
                shade:0.4,
                content:"<div class='layui-inline' style='margin:40px 0px 0px 40px;z-index: 10'>" +
                    "<label class='layui-form-label'>商品分类：</label>" +
                    "<div class='layui-input-block'>" +
                    "<input type='text' name='categroyName' id='categroyName' class='layui-input' placeholder='商品分类'/>" +
                    "</div>" +
                    "</div>",
                btn:['添加','取消'],
                yes:function(){
                    //获取当前登陆人员的信息
                    var create=localStorage.getItem("user");
                    create=JSON.parse(create);//将获取json字符串转json对象

                    var categroyName=$("#categroyName").val();
                    if(categroyName===""||categroyName===null||categroyName===undefined) {
                        layer.msg("分类不能为空", {icon: 5});
                    }else{
                        $.ajax({
                            url:"/SyOperationController/addProductCategory",
                            type:"post",
                            dataType:"json",
                            data:{"parentId":parentId,"categroyName":categroyName,"createUser":create.user_id,"categroyState":1},
                            success:function(data){
                                if(data.code==0){
                                    location.reload();
                                }
                            }
                        });
                    }

                }
            });
        });

        //修改节点
        $("#m_check").bind("click",function(){
            var id = ZtreeTile.id
            layer.open({
                type:1,
                id:2,
                title:"修改节点",
                area:['420px','200px'],
                offset:'auto',
                shade:0.4,
                content:"<div class='layui-inline' style='margin:40px 0px 0px 40px;z-index: 10'>" +
                    "<label class='layui-form-label'>商品名称：</label>" +
                    "<div class='layui-input-block'>" +
                    "<input type='text' name='categroyName' id='categroyName' class='layui-input' placeholder='商品分类'/>" +
                    "</div>" +
                    "</div>",
                btn:['修改','取消'],
                yes:function(){
                    //获取当前登陆人员的信息
                    var create=localStorage.getItem("user");
                    create=JSON.parse(create);//将获取json字符串转json对象

                    var categroyName=$("#categroyName").val();

                    if(categroyName===""||categroyName===null||categroyName===undefined) {
                        layer.msg("分类不能为空", {icon: 5});
                    }else{
                        $.ajax({
                            url:"/SyOperationController/updProductCategory",
                            type:"post",
                            dataType:"json",
                            data:{"categroyName":categroyName,"updateUser":create.user_id,"id":id},
                            success:function(data){
                                if(data.code==0){
                                    location.reload();
                                }
                            }
                        });
                    }

                }
            });
        });

        //删除节点
        $("#m_del").bind("click",function() {
            $.ajax({
                url:"/SyOperationController/delProductCategory",
                type:"post",
                dataType:"json",
                data:{"id":ZtreeTile.id},
                success:function(data){
                    if(data.code==0){
                        location.reload();
                    }
                }
            });
        });

        function resetTree() {
            hideRMenu();
            $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
        }

        var zTree, rMenu;
        $(document).ready(function(){
            $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
            zTree = $.fn.zTree.getZTreeObj("treeDemo");
            rMenu = $("#rMenu");
        });
        var setting={
            /*check: {
                enable: true,
                chkStyle: "checkbox",//显示 checkbox 选择框，默认checkbox可选择值radio
            },*/
            callback: {
                onRightClick: OnRightClick,
                onClick: zTreeOnClick,
            },
            view: {
                dblClickExpand: false,
                showIcon: false,

            },
        };
        var zTreeNodes=data;
        var city = $.fn.zTree.init($("#treeDemo"), setting, zTreeNodes);
    });
}